package com.sensetime.mediacodec;

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaCodec;
import android.media.MediaFormat;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.senseauto.subgroup.autocameralib.callback.CameraImageCallback;
import com.senseauto.subgroup.autocameralib.cameraV2.CameraV2Proxy;
import com.senseauto.subgroup.autocameralib.model.CameraOptions;
import com.senseauto.subgroup.autocommonlib.utilcode.util.ImageUtils;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;

public class MainActivity extends AppCompatActivity implements CameraImageCallback, EncoderCallback, View.OnClickListener {
    SurfaceView surfaceView;
    H264MediaCodecAsyncEncoder h264Encoder;
    CameraV2Proxy cameraV2Proxy;
    int requestCode = 101;
    boolean isStartEncoder = false;
    String permissions[] = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO};
    String TAG = "MainActivity";
    Button recordBtn;

    //平板和车机这三个属性会不同
    /*int cameraId = 45;
    int imageWidth = 1600;
    int imageHeight = 1300;*/
    int cameraId = 0;
    int imageWidth = 1920;
    int imageHeight = 1080;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        surfaceView = findViewById(R.id.surface);
        recordBtn = findViewById(R.id.start);
        recordBtn.setOnClickListener(this);
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
                    checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
                    checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED &&
                    checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                Log.e(TAG, "权限申请");
                requestPermissions(permissions, requestCode);
            } else {
                Log.e(TAG, "权限有了1");
                initSurface();
            }
        } else {
            Log.e(TAG, "权限有了2");
            initSurface();
        }
    }

    public void initCamera(Surface surface) {
        CameraOptions options = new CameraOptions();
        options.setImgWidth(imageWidth);
        options.setImgHeight(imageHeight);
        options.setCameraId(cameraId);
        options.setImageFormat(ImageUtils.ImageFormat.NV21);
        cameraV2Proxy = new CameraV2Proxy(getApplicationContext(), options);
        cameraV2Proxy.setPreview(surface);
        cameraV2Proxy.startCameraThread();
        cameraV2Proxy.initOption();
        cameraV2Proxy.openCamera();

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        cameraV2Proxy.startPreview();
        cameraV2Proxy.setCameraImageCallback(this);
    }

    public void initSurface() {
        //surfaceView相当于一个画框
        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
                //surfaceView的surface就相当于画布，在这个方法里就可以拿到一个准备好了的空白画布

                Surface surface = surfaceHolder.getSurface();
                initCamera(surface);

            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {
                Log.e(TAG, "surfaceChanged=>" + i1 + " " + i2);
            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
                Log.e(TAG, "surfaceDestroyed=>");
            }
        });

    }
    private void startRecord(){
        File file = FileUtils.getMp4File(getApplicationContext());
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String path = file.getAbsolutePath();
        Log.e(TAG, "path=" + path);
        h264Encoder = new H264MediaCodecAsyncEncoder(imageWidth, imageHeight);
        h264Encoder.setEncoderCallback(MainActivity.this);
        h264Encoder.setOutputPath(path);
        h264Encoder.startEncoder();
    }
    public void stopRecord(){
        if(h264Encoder!=null){
            h264Encoder.stopEncoder();
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (this.requestCode == requestCode) {
            if (grantResults.length == permissions.length) {
                initSurface();
            } else {
                Log.e(TAG, "grantResults.length=" + grantResults.length);
            }
        } else {
            Log.e(TAG, "requestCode不同");
        }
    }
    //摄像头回调--start
    @Override
    public void onReadImageData(@Nullable byte[] bytes, int i, int i1) {
        if(h264Encoder!=null && isStartEncoder){
            h264Encoder.putData(bytes);
        }

    }

    @Override
    public void onException(@NonNull Exception e) {
        Log.e(TAG, "onException=>"+e.getMessage());
    }
    //摄像头回调--end

    //录制回调--start
    @Override
    public void outputMediaFormatChanged(int type, MediaFormat mediaFormat) {

    }

    @Override
    public void onEncodeOutput(int type, ByteBuffer byteBuffer, MediaCodec.BufferInfo bufferInfo) {

    }

    @Override
    public void onStop(int type) {
        Log.e(TAG, "停止录制了onStop");
    }

    @Override
    public void onClick(View v) {
        if(isStartEncoder){
            recordBtn.setText("开始录制");
            isStartEncoder = false;
            stopRecord();
        }else{
            recordBtn.setText("录制中..");
            isStartEncoder = true;
            startRecord();
        }
    }
    //录制回调--end

}